package com.xbongbong.workorder.service.impl;/*/*/

import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.WorkOrderErrorCodeEnum;
import com.xbongbong.pro.workorder.pojo.WorkOrderTemplateDetailWorkflowPojo;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.model.WorkOrderStageModel;
import com.xbongbong.workorder.service.WorkOrderStageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 * @date 2019/3/18 15:03
 * @since v1.0
 * @version v1.0
 */
@Service("workOrderStageService")
public class WorkOrderStageServiceImpl implements WorkOrderStageService {

    private static final Logger LOG = LoggerFactory.getLogger(WorkOrderStageServiceImpl.class);

    @Resource
    private WorkOrderStageModel workOrderStageModel;

    @Override
    public List<WorkOrderTemplateDetailWorkflowPojo> saveStages(List<WorkOrderTemplateDetailWorkflowPojo> workStage, Long templateId, String corpid, boolean isNew) throws XbbException {
        List<WorkOrderTemplateDetailWorkflowPojo> oldWorkStageList = new ArrayList<>();
        if (!isNew) {
            //不是新建需要删除原有的阶段
            List<WorkOrderStageEntity> workOrderStageEntities = workOrderStageModel.workOrderStageListByTemplateId(corpid, templateId);
            if (workOrderStageEntities.size() != 0) {
                Set<Long> stageIds = new HashSet<>();
                for (WorkOrderStageEntity entity : workOrderStageEntities) {
                    stageIds.add(entity.getId());
                    WorkOrderTemplateDetailWorkflowPojo flowPojo = BeanUtil.copyProperties(entity, WorkOrderTemplateDetailWorkflowPojo.class, false);
                    //秒转为小时
                    Double expectedTime = Arith.div(entity.getExpectedTime(), TimeConstant.SECONDS_PER_HOUR, 2);
                    flowPojo.setExpectedTime(expectedTime);
                    //为保证和workStage内的对象一致（workStage内无sort，此处如果不set空进去的话，就算页面没更新，也会因为两个对象内sort的不同<一个有sort、一个没有>而被默认为有更改）
                    flowPojo.setSort(null);
                    oldWorkStageList.add(flowPojo);
                }
                Set<Long> nowStageIds = new HashSet<>();
                for (WorkOrderTemplateDetailWorkflowPojo pojo : workStage) {
                    nowStageIds.add(pojo.getId());
                }
                Set<Long> delIds = new HashSet<>(stageIds);
                stageIds.retainAll(nowStageIds);
                delIds.removeAll(stageIds);
                if (delIds.size() > 0) {
                    Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put("corpid", corpid);
                    param.put("idIn", delIds);
                    workOrderStageModel.delete(param);
                }
            }
        }
        Integer sort = 0;
        for (WorkOrderTemplateDetailWorkflowPojo flow : workStage) {
            WorkOrderStageEntity stageEntity = new WorkOrderStageEntity();
            if (!Objects.equals(flow.getId(), 0L)) {
                stageEntity.setId(flow.getId());
            }
            stageEntity.setTemplateId(templateId);
            stageEntity.setCorpid(corpid);
            if (flow.getName() != null && flow.getName().length() >= 20) {
                throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222058);
            }
            stageEntity.setName(flow.getName());
            stageEntity.setSort(sort++);
            stageEntity.setIsLast(flow.getIsLast());
            stageEntity.setRefRobId(flow.getRefRobId());
            stageEntity.setRefRobName(flow.getRefRobName());
            stageEntity.setRefRobType(flow.getRefRobType());
            stageEntity.setUserAvatar(flow.getUserAvatar());

            Double expectedTime = flow.getExpectedTime() * 3600;
            stageEntity.setExpectedTime(expectedTime.intValue());
            stageEntity.setDel(0);
            stageEntity.setRuleId(flow.getRuleId());
            workOrderStageModel.save(stageEntity);
        }
        // TODO: 2019/3/18
        //需要更新tb_saas_work_order_data的expected_time字段
        return oldWorkStageList;
    }

    @Override
    public List<WorkOrderStageEntity> getStageList(Long templateId, String corpid,Boolean filterDel) {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        if (filterDel){
            param.put("del",0);
        }
        param.put("templateId",templateId);
        param.put("orderByStr","sort");
        return workOrderStageModel.findEntitys(param);
    }

    @Override
    public WorkOrderStageEntity getNextStage(Long templateId,Long nowStageId, String corpid) {
        WorkOrderStageEntity nowStageEntity = workOrderStageModel.getByKey(nowStageId,corpid);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("nowSort",nowStageEntity.getSort());
        param.put("templateId",templateId);
        return workOrderStageModel.getNextStage(param);
    }

    @Override
    public WorkOrderStageEntity getPreStage(Long templateId, Long nowStageId, String corpid) {
        WorkOrderStageEntity nowStageEntity = workOrderStageModel.getByKey(nowStageId,corpid);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("nowSort",nowStageEntity.getSort());
        param.put("templateId",templateId);
        return workOrderStageModel.getPreStage(param);
    }

    @Override
    public Map<Long, Integer> getExpectedTimeMap(String corpid, Long templateId) {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("templateId",templateId);
        List<WorkOrderStageEntity> workOrderStageEntityList = workOrderStageModel.findEntitys(param);
        Map<Long,Integer> expectedTimeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (WorkOrderStageEntity entity : workOrderStageEntityList){
            expectedTimeMap.put(entity.getId(),entity.getExpectedTime());
        }
        return expectedTimeMap;
    }

    @Override
    public Map<Long, String> getSatgeNameMap(Long templateId, String corpid) {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("templateId",templateId);
        param.put("orderByStr","sort");
        List<WorkOrderStageEntity> workOrderStageEntityList =  workOrderStageModel.findEntitys(param);
        Map<Long,String> stageNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (WorkOrderStageEntity entity : workOrderStageEntityList){
            stageNameMap.put(entity.getId(),entity.getName());
        }
        stageNameMap.put(0L,I18nMessageUtil.getMessage(I18nStringConstant.FREE_FLOW));
        return stageNameMap;
    }

    @Override
    public List<ItemPoJo> getStageNameItemList(Long templateId, String corpid) {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("templateId",templateId);
        param.put("orderByStr","sort");
        List<WorkOrderStageEntity> workOrderStageEntityList =  workOrderStageModel.findEntitys(param);
        List<ItemPoJo> itemPoJoList = new ArrayList<>();
        for (WorkOrderStageEntity entity : workOrderStageEntityList){
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setValue(entity.getId());
            itemPoJo.setText(entity.getName());
            itemPoJoList.add(itemPoJo);
        }
        if (workOrderStageEntityList.isEmpty()){
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setValue(0L);
            itemPoJo.setText(I18nMessageUtil.getMessage(I18nStringConstant.FREE_FLOW));
            itemPoJoList.add(itemPoJo);
        }
        return itemPoJoList;
    }

    @Override
    public List<Long> getPreStageList(Long templateId, Long stageId, String corpid) {
        WorkOrderStageEntity nowStageEntity = workOrderStageModel.getByKey(stageId,corpid);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("nowSort",nowStageEntity.getSort());
        param.put("templateId",templateId);
        return workOrderStageModel.getPreStageList(param);
    }

    @Override
    public List<WorkOrderStageEntity> getStagesByTemplateIdIn(Collection<Long> templateIds, String corpid, Boolean filterDel) {
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        if (filterDel){
            param.put("del",0);
        }
        param.put("templateIdIn", templateIds);
        return workOrderStageModel.findEntitys(param);
    }

    @Override
    public WorkOrderStageEntity getFirstStage(Long templateId, String corpid) {
        return workOrderStageModel.getFirstStage(templateId,corpid);
    }
}
